package com.irony.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.irony.oss.service.FileService;
import com.irony.oss.utils.ConstantYmlUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    //上传代码
    @Override
    public String uploadOssFile(MultipartFile file) {

        String endpoint = ConstantYmlUtils.END_POINT;
        String accessKeyId = ConstantYmlUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantYmlUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantYmlUtils.BUCKET_NAME;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            //获取文件名称
            String filename = file.getOriginalFilename();
            //在文件名中添加随机的唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid + filename;
            //路径可以按日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd/");
            filename = datePath + filename;
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传后的路径返回需要自己手动拼接
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
